import React, { useState, useEffect } from'react';
import { Breadcrumb, Form, Input, Select, DatePicker, Button, Table, message, Modal, InputNumber } from 'antd';
import { getorder, getorderinfo, updateorder } from "../../api/account";
import style from './index.module.less';
import dayjs from 'dayjs';

const { Option } = Select;
const { RangePicker } = DatePicker;

const Order = () => {
    // 表单状态
    const [form] = Form.useForm();
    // 搜索表单数据状态
    const [orderData, setOrderData] = useState({
        currentPage: 1,
        pageSize: 5,
        orderNo: '',
        consignee: '',
        phone: '',
        orderState: '',
        date: []
    });
    // 订单列表数据状态
    const [orderData1, setOrderData1] = useState([]);
    // 总记录数状态
    const [total, setTotal] = useState(0);
    // 编辑弹窗可见性状态
    const [dialogFormVisible, setDialogFormVisible] = useState(false);
    // 编辑表单数据状态
    const [editFormData, setEditFormData] = useState({
        id: '',
        orderNo: '',
        orderTime: '',
        phone: '',
        consignee: '',
        deliverAddress: '',
        deliveryTime: '',
        remarks: '',
        orderAmount: '',
        orderState: ''
    });
    // 新增状态，用于显示搜索结果的行数
    const [searchResultCount, setSearchResultCount] = useState(0);

    // 格式化时间函数
    const formatDate = (date) => {
        return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
    };

    // 获取订单列表函数
    const order = async (orderdata) => {
        try {
            // 处理日期范围格式
            const formattedOrderData = {
              ...orderdata,
                date: orderdata.date.map(date => date? dayjs(date).format('YYYY-MM-DD') : null)
            };
            const data = await getorder(formattedOrderData);
            setTotal(data.total);
            setOrderData1(data.data);
            // 更新搜索结果的行数
            setSearchResultCount(data.data.length);
        } catch (error) {
            message.error('获取订单列表失败');
            console.error('获取订单列表失败:', error);
        }
    };

    useEffect(() => {
        order(orderData);
    }, [orderData]);

    // 处理每页数量变化函数
    const handleSizeChange = (val) => {
        setOrderData({
          ...orderData,
            currentPage: 1,
            pageSize: val
        });
    };

    // 处理当前页码变化函数
    const handleCurrentChange = (val) => {
        setOrderData({
          ...orderData,
            currentPage: val
        });
    };

    // 编辑函数，打开编辑弹窗并填充数据
    const handleEdit = (row) => {
        setDialogFormVisible(true);
        setEditFormData({
            id: row.id,
            orderNo: row.orderNo,
            orderTime: row.orderTime,
            phone: row.phone,
            consignee: row.consignee,
            deliverAddress: row.deliverAddress,
            deliveryTime: row.deliveryTime,
            remarks: row.remarks,
            orderAmount: row.orderAmount,
            orderState: row.orderState
        });
    };

    // 确定函数，提交编辑表单并更新订单信息
    const confirm = async () => {
        try {
            await updateorder(editFormData);
            setDialogFormVisible(false);
            order(orderData);
            message.success('订单修改成功');
        } catch (error) {
            message.error('订单修改失败');
            console.error('订单修改失败:', error);
        }
    };

    // 请求查看订单详情函数
    const orderdetail = async (orderid) => {
        try {
            await getorderinfo(orderid);
        } catch (error) {
            console.error('获取订单详情失败:', error);
        }
    };

    // 查看函数，展示订单详情弹窗
    const handleClick = (row) => {
        orderdetail({ id: row.id });
        Modal.info({
            title: '详情信息',
            content: (
                <div>
                    <p><strong>收货人：</strong>{row.consignee}</p>
                    <p><strong>配送地址：</strong>{row.deliverAddress}</p>
                    <p><strong>配送时间：</strong>{formatDate(row.orderTime)}</p>
                    <p><strong>订单价格：</strong>{row.orderAmount}</p>
                    <p><strong>订单号：</strong>{row.orderNo}</p>
                    <p style={{ width: '100px' }}><strong>订单状态：</strong>{row.orderState}</p>
                    <p><strong>到达时间：</strong>{formatDate(row.deliveryTime)}</p>
                    <p><strong>电话：</strong>{row.phone}</p>
                    <p><strong>备注：</strong>{row.remarks}</p>
                </div>
            ),
            dangerouslyUseHTML: true
        });
    };

    const columns = [
        {
            title: '订单号',
            dataIndex: 'orderNo',
            key: 'orderNo',
            width: 80
        },
        {
            title: '下单时间',
            dataIndex: 'orderTime',
            key: 'orderTime',
            render: (text) => formatDate(text),
            width: 150
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            width: 120
        },
        {
            title: '收货人',
            dataIndex: 'consignee',
            key: 'consignee',
            width: 100
        },
        {
            title: '配送地址',
            dataIndex: 'deliverAddress',
            key: 'deliverAddress',
            width: 120
        },
        {
            title: '送达时间',
            dataIndex: 'deliveryTime',
            key: 'deliveryTime',
            render: (text) => formatDate(text),
            width: 150
        },
        {
            title: '用户备注',
            dataIndex:'remarks',
            key:'remarks',
            width: 100
        },
        {
            title: '订单金额',
            dataIndex: 'orderAmount',
            key: 'orderAmount',
            width: 100
        },
        {
            title: '订单状态',
            dataIndex: 'orderState',
            key: 'orderState',
            width: 100
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <div>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleClick(record)}
                    >
                        查看
                    </Button>
                    <Button
                        type="link"
                        size="small"
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                </div>
            ),
            width: 80
        }
    ];

    return (
        <div className={style.main}>
            <div className={style.table}>
                <Form
                    form={form}
                    name="orderForm"
                    initialValues={orderData}
                    className={style['demo-form-inline']}
                    style={{ display: 'flex', flexWrap: 'wrap' }}
                    onFinish={(values) => {
                        setOrderData({
                          ...values,
                            currentPage: 1,
                            pageSize: orderData.pageSize
                        });
                    }}
                >
                    <Form.Item
                        name="orderNo"
                        label="订单号"
                        style={{ marginRight: 16 }}
                    >
                        <Input placeholder="请输入订单号" />
                    </Form.Item>
                    <Form.Item
                        name="consignee"
                        label="收货人"
                        style={{ marginRight: 16 }}
                    >
                        <Input placeholder="请输入收货人" />
                    </Form.Item>
                    <Form.Item
                        name="phone"
                        label="手机号"
                        style={{ marginRight: 16 }}
                    >
                        <Input placeholder="请输入手机号" />
                    </Form.Item>
                    <Form.Item
                        name="orderState"
                        label="订单状态"
                        style={{ marginRight: 0 }}
                    >
                        <Select placeholder="请选择订单状态">
                            <Option value="已受理">已受理</Option>
                            <Option value="派送中">派送中</Option>
                            <Option value="已完成">已完成</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="date"
                        label="选择时间"
                        style={{ width: '100%' }}
                    >
                        <RangePicker
                            placeholder={['开始日期', '结束日期']}
                        />
                    </Form.Item>
                    <Button
                        type="primary"
                        htmlType="submit"
                        className={style['demo-range']}
                    >
                      {/* 表格重新刷新只显示搜索之后的内容 */}
                        搜索
                    </Button>
                </Form>
                <Table
                    columns={columns}
                    dataSource={orderData1}
                    size="middle"
                    rowKey="id"
                    pagination={{
                        current: orderData.currentPage,
                        pageSize: orderData.pageSize,
                        total: total,
                        onChange: handleCurrentChange,
                        onShowSizeChange: handleSizeChange
                    }}
                    className={style['el-table']}
                />
                <Modal
                    title="订单详情"
                    open={dialogFormVisible}
                    onCancel={() => setDialogFormVisible(false)}
                    footer={[
                        <Button key="cancel" onClick={() => setDialogFormVisible(false)}>取消</Button>,
                        <Button key="confirm" type="primary" onClick={confirm}>确定</Button>
                    ]}
                >
                    <Form
                        form={form}
                        name="editOrderForm"
                        initialValues={editFormData}
                    >
                        <Form.Item
                            name="consignee"
                            label="收货人"
                        >
                            <Input placeholder="收货人" />
                        </Form.Item>
                        <Form.Item
                            name="deliverAddress"
                            label="派送地址"
                        >
                            <Input placeholder="派送地址" />
                        </Form.Item>
                        <Form.Item
                            name="orderTime"
                            label="配送时间"
                        >
                            <Input placeholder="配送时间" />
                        </Form.Item>
                        <Form.Item
                            name="orderAmount"
                            label="订单价格"
                        >
                            <InputNumber placeholder="订单价格" />
                        </Form.Item>
                        <Form.Item
                            name="orderNo"
                            label="订单号"
                        >
                            <Input placeholder="订单号" />
                        </Form.Item>
                        <Form.Item
                            name="deliveryTime"
                            label="到达时间"
                        >
                            <Input placeholder="到达时间" />
                        </Form.Item>
                        <Form.Item
                            name="phone"
                            label="电话"
                        >
                            <Input placeholder="电话" />
                        </Form.Item>
                        <Form.Item
                            name="remarks"
                            label="备注"
                        >
                            <Input placeholder="备注" />
                        </Form.Item>
                        <Form.Item
                            name="orderState"
                            label="订单状态"
                        >
                            <Select placeholder="订单状态">
                                <Option value="已完成">已完成</Option>
                                <Option value="已受理">已受理</Option>
                                <Option value="派送中">派送中</Option>
                            </Select>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        </div>
    );
};

export default Order;
    